// 删除文集接口
import joi from 'joi'
import pool from '@/server/db'
import { ResultSetHeader } from 'mysql2'

export default defineEventHandler(async event => {
  // 判断用户是否登录
  if (!event.context.userinfo) return r('请登录')
  const { uid } = event.context.userinfo

  // 数据校验
  const body = await readBody(event)
  const schema = joi.object({
    nid: joi.number().required(),
  })
  try {
    const value = schema.validate(body)
  } catch (error) {
    return r('文集id不能为空')
  }

  // 删除文集
  try {
    const [rows] = await pool.execute(
      'DELETE FROM `notebooks` WHERE `uid` = ? AND `id` = ?',
      [uid, body.nid]
    )
    if ((rows as ResultSetHeader).affectedRows === 0) {
      return r('删除文集失败')
    }
    return r('删除成功', 1)
  } catch (error) {
    return r('文集删除失败:' + error)
  }
})
